<?php
class Cms_CreateUpdate_Pgsql extends Cms_Adapter_Pgsql_Abstract
	implements Cms_CreateUpdate_Interface
{
	public function getForeignList($reference)
	{
		// Foreign key string
		list($foreign) = explode(' = ', $reference);
	
		// Params
		list($schema, $table, $field) = explode('.', $foreign);
		
		// Cms Instance to foreign table
		$cms = Cms::factory('CreateUpdate', $table, $schema);
		$repCol = $cms->getAdapter()->representativeTableColumn();
		
		// Query
		$sql = $this->_db->select()
			->from(array($table), array($field, $repCol), $schema)
			->order($repCol);
		
		$data = array('Selecione!');
		return $data += $this->_db->fetchPairs($sql);
}
	
	public function getNmList()
	{
		// Will be verified each table just one time
		$eachTable = array();
		
		$nms = array();
		
		// Loop under tables that make reference to the matter table
		foreach($this->getDependentTables() as $keyDep => $dep)
		{
			// Nm table
			list(
				$nmDep['schema'],
				$nmDep['table'],
				$nmDep['field']
			) = explode('.', $dep['from']);
			
			// Local column that this NM makes reference
			list($nmDep['local']) = array_reverse(explode('.', $dep['to']));
			
			// Nm table instance
			$cms = Cms::factory('CreateUpdate', $nmDep['table'], $nmDep['schema']);
			
			// Is a NM table?
			// This table was not verified yet?
			if(
				$cms->getAdapter()->isManyToMany() &&
				!isset($eachTable[$nmDep['schema'].'.'.$nmDep['table']])
			) {
				// Create index only for flag
				$eachTable[$nmDep['schema'].'.'.$nmDep['table']] = true;

				$nmColsAndViewName = $this->nmColsAndViewTableName($cms);
				$nmDep['view_table'] = $nmColsAndViewName['view_table'];
				
				// Nm table informations
				$nms[$keyDep] = array(
					'info' => $nmDep,
					'columns' => $nmColsAndViewName['columns']
				);
			}
		}
		return $nms;
	}
	
	public function getValidationTypes(array $data)
	{
		$rules = array();
		
		foreach($data as $column => $colType)
		{
			$param = null;
			
			// If have some ( in the string
			if(preg_match('/\(/', $colType)) {
				list($colType, $param) = explode('(', $colType);
				$param = rtrim($param, ')');
				$param = str_replace('[]', '', $param);
			}
			
			switch($colType) {
				case 'character':
				case 'character varying':
					
					$rules[$column]['maxlen'][] = $param;
					
					break;
				case 'integer':
					
					$rules[$column]['numeric'][] = true;
					
					break;
			}
			
			// Comming here all columns are required
			$rules[$column]['required'][] = true;
		}
		
		return $rules;
	}
}
